package model

import (
	"cms/libs"
	"errors"
	"github.com/jinzhu/gorm"
	config "github.com/spf13/viper"
	"math"
)

type Adv struct {
	gorm.Model
	Position string `gorm:"column:position" json:"position" form:"position" validate:"required"`
	Title    string `gorm:"column:title" json:"title" form:"title" validate:"required"`
	Content  string `gorm:"column:content" json:"content" form:"content" validate:"required"`
	Sort     uint   `gorm:"column:sort" json:"sort" form:"sort"`
}

func (this *Adv) List(page int) ([]Adv, int, int) {
	var data = []Adv{}
	var totalCount int
	db := libs.DB

	limit := config.GetInt("pagination.PageSize")
	offset := (page - 1) * limit
	db.Find(&data).Count(&totalCount)
	db.Offset(offset).Limit(limit).Order("id desc").Find(&data)
	totalPages := int(math.Ceil(float64(totalCount) / float64(limit)))
	return data, totalCount, totalPages
}

func (this *Adv) SearchList(ids []string) []Adv {
	var data = []Adv{}
	db := libs.DB
	db.Where("id in (?)", ids).Order("id desc").Find(&data)
	return data
}

func (this *Adv) Info(id uint) (Adv, error) {
	var adv Adv
	db := libs.DB

	if db.Where("id = ?", id).First(&adv).RecordNotFound() {
		return Adv{}, errors.New("内容未找到")
	}
	return adv, nil
}

func (this *Adv) InfoByPosition(position string) (Adv, error) {
	var adv Adv
	db := libs.DB
	if db.Where("position = ?", position).First(&adv).RecordNotFound() {
		return Adv{}, errors.New("内容未找到")
	}
	return adv, nil
}

func (this *Adv) Add(postValues map[string][]string) error {
	var adv Adv
	db := libs.DB

	if err := libs.FormDecode(&adv, postValues); err != nil {
		return err
	}
	if err := libs.Validate(adv); err != nil {
		return err
	}
	if !db.Where("title = ? ", adv.Title).First(&Adv{}).RecordNotFound() {
		return errors.New("该标题已经存在")
	}

	if err := db.Create(&adv).Error; err != nil {
		return err
	}
	return nil
}

func (this *Adv) Update(postValues map[string][]string) error {
	var adv Adv
	db := libs.DB

	if err := libs.FormDecode(&adv, postValues); err != nil {
		return err
	}
	if err := libs.Validate(adv); err != nil {
		return err
	}
	if !db.Where("title = ? and id != ?", adv.Title, adv.ID).First(&Adv{}).RecordNotFound() {
		return errors.New("该标题已经存在")
	}
	if db.Where("id = ? ", adv.ID).First(&Adv{}).RecordNotFound() {
		return errors.New("未查询到内容id")
	}

	if err := db.Save(&adv).Error; err != nil {
		return err
	}
	return nil
}

func (this *Adv) Del(id uint) error {
	var adv Adv
	db := libs.DB

	if err := db.Where("id = ?", id).Delete(&adv).Error; err != nil {
		return err
	}
	return nil
}
